package org.shop.controller.supplier;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.CashDraws;
import org.shop.entity.OrderSettlements;
import org.shop.entity.Supplier;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.CashDrawsService;
import org.shop.service.OrderSettlementsService;
import org.shop.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("supplier")
public class SupplierMoneyController {
	
	private static Logger logger = LogManager.getLogger(SupplierMoneyController.class);
	
	@Autowired
	private OrderSettlementsService orderSettlementsService;
	@Autowired
	private CashDrawsService cashDrawsService;
	@Autowired
	private SupplierService supplierService;
	/**
	 * 获取提现记录信息
	 * @param req
	 * @return
	 */
	@RequestMapping("getCashDrawsInfoList")
	@ResponseBody
	public Map<String,Object> getCashDrawsInfoList(HttpServletRequest req){
		Map<String,Object> map = new HashMap<String,Object>();
	 	String currentPage = req.getParameter("offset");
        String pageSize = req.getParameter("limit");
        String startTime = req.getParameter("startTime");
        String endTime = req.getParameter("endTime") == null|| "".equals(req.getParameter("endTime")) ? "" : req.getParameter("endTime")+"23:59:59";
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try{
			Supplier supplier=supplierService.findSupplierByUserId(ud.getUserId());
			Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("startPage", Integer.parseInt(currentPage));
            paramMap.put("pageSize", Integer.parseInt(pageSize));
            paramMap.put("targetType", 1);
            paramMap.put("targetId", supplier.getSupplierId());
            paramMap.put("startTime", startTime);
            paramMap.put("endTime", endTime);
            map = cashDrawsService.getCashDrawsInfo(paramMap);
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
	
	/**
	 * 获取金额信息
	 * @param req
	 * @return
	 */
	@RequestMapping("getOrderSettlementsInfo")
	@ResponseBody
	public Map<String,Object> getOrderSettlementsInfo(HttpServletRequest req){
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,Object> paramMap = new HashMap<String,Object>();
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			Supplier supplier=supplierService.findSupplierByUserId(ud.getUserId());
			paramMap.put("supplierId", supplier.getSupplierId());
			OrderSettlements orderSettlements = orderSettlementsService.getOrderSettlements(paramMap);
			if(ObjectUtils.isEmpty(orderSettlements)) {
				map.put("orderSettlements", null);
			}else {
				map.put("orderSettlements", orderSettlements);
			}
		}catch(Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			map.put("orderSettlements", null);
		}
		return map;
	}
	
	/**
	 * 提现
	 * @param req
	 * @return
	 */
	@RequestMapping("withdrawal")
	@ResponseBody
	public Map<String,Object> withdrawal(HttpServletRequest req){
		Map<String,Object> map = new HashMap<String,Object>();
		Long settlementId = Long.parseLong(req.getParameter("settlementId"));
		String price = req.getParameter("price");
		String cashRemarks = req.getParameter("cashRemarks");
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			OrderSettlements osInfo = orderSettlementsService.selectByPrimaryKey(settlementId);
			if(osInfo.getSupplierPrice().compareTo(new BigDecimal(price)) >= 0) {
				osInfo.setSettlementId(settlementId);
				osInfo.setSupplierPrice(osInfo.getSupplierPrice().subtract(new BigDecimal(price)));
				osInfo.setUpdateDate(new Date());
				int num = orderSettlementsService.updateByPrimaryKeySelective(osInfo );
				if(num>0) {
					CashDraws cd = new CashDraws();
					cd.setCashRemarks(cashRemarks);
					cd.setTargetType((byte) 1);
					cd.setMoney(new BigDecimal(price));
					cd.setTargetId(ud.getMerchantId());
					cd.setAccType((byte) 2);
					cashDrawsService.insertSelective(cd);
				}
				map.put("state", num);
				map.put("msg", "微信提现成功");
			}else {
				map.put("state", 0);
				map.put("msg", "提现的金额大于可用余额~");
			}
		}catch(Exception e) {
			map.put("state", 0);
			map.put("msg", "微信提现失败");
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
}
